package study.nzy.com.studydemo;

import android.os.Bundle;
import android.app.Activity;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.widget.ListView;
import android.widget.SimpleAdapter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class DynamicActivity extends Activity {

    String fruitName[]={"苹果","香蕉","樱桃","葡萄","芒果","桔子","梨","菠萝","草莓","西瓜"};
    //定义图片资源数组
    int image[] = {R.drawable.apple_pic,
            R.drawable.banana_pic,
            R.drawable.cherry_pic,
            R.drawable.grape_pic,
            R.drawable.mango_pic,
            R.drawable.orange_pic,
            R.drawable.pear_pic,
            R.drawable.pineapple_pic,
            R.drawable.strawberry_pic,
            R.drawable.watermelon_pic};

    ListView listView;
    SimpleAdapter simpleAdapter;
    List<Map<String,Object>> imageList;
    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg.what == 1){
                simpleAdapter.notifyDataSetChanged();
            }
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dynamic);
        listView = findViewById(R.id.listview);
        String[] from ={"img","name"};
        int[] to ={R.id.iv_fruit,R.id.tv_fruit_name};
        imageList = new ArrayList<Map<String,Object>>();
        for(int i=0;i<image.length;i++){
            Map<String,Object> map = new HashMap<String,Object>();
            map.put("img",image[i]);
            map.put("name",fruitName[i]);
            imageList.add(map);
        }
        simpleAdapter = new SimpleAdapter(this,imageList,R.layout.item_fruit,from,to);
        listView.setAdapter(simpleAdapter);

        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true){
                    SystemClock.sleep(3000);
                    for(int i=0;i<image.length;i++){
                        Map<String,Object> map = new HashMap<String,Object>();
                        map.put("img",image[i]);
                        map.put("name",fruitName[i]);
                        imageList.add(map);
                    }
                    handler.sendEmptyMessage(1);
                }
            }
        }).start();
    }
}